package com.tronsis.distribution.activity.me.order;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.CollectionWayActivity;
import com.tronsis.distribution.activity.me.PaymentVoucherActivity;
import com.tronsis.distribution.bean.AskBuyDetailBean;
import com.tronsis.distribution.bean.PayeeMethodBean;
import com.tronsis.distribution.bean.UploadFileBean;
import com.tronsis.distribution.biz.factory.FileBizFactory;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.http.Url;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.IntentUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

public class OfflinePayActivity extends ToolBarBaseActivity {

    @BindView(R.id.tv_leader_name)
    TextView mTvLeaderName;
    @BindView(R.id.tv_payee)
    TextView mTvPayee;
    @BindView(R.id.iv_right1)
    ImageView mIvRight1;
    @BindView(R.id.ll_pay_type)
    LinearLayout mLlPayType;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_account)
    TextView mTvAccount;
    @BindView(R.id.iv_right3)
    ImageView mIvRight3;
    @BindView(R.id.ll_pay_voucher)
    LinearLayout mLlPayVoucher;
    @BindView(R.id.tv_label_pay_image)
    TextView mTvLabelPayImage;
    @BindView(R.id.rv_user_upload)
    RecyclerView mRvUserUpload;
    @BindView(R.id.ll_pay_image)
    LinearLayout mLlPayImage;
    @BindView(R.id.ll_leader_name)
    LinearLayout mLlLeaderName;

    private ArrayList<ImageItem> mImageList = new ArrayList<>();
    private CommonAdapter<ImageItem> mPayImageAdapter;
    private String mPayeeId;
    private AskBuyDetailBean mAskBuyDetailBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_pay);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.order_detail));
        initImageRv();

        mAskBuyDetailBean = (AskBuyDetailBean) getIntent().getSerializableExtra("AskBuyDetailBean");
        if (mAskBuyDetailBean != null) {
            if (mAskBuyDetailBean.getLeaderName() != null) {
                mLlLeaderName.setVisibility(View.VISIBLE);
                mTvLeaderName.setText(mAskBuyDetailBean.getLeaderName());
            } else {
                if (StringUtil.isEquals(mAskBuyDetailBean.getPayType(), "微信支付")) {
                    mLlLeaderName.setVisibility(View.GONE);
                } else {
                    mLlLeaderName.setVisibility(View.VISIBLE);
                }
                mTvLeaderName.setText(mAskBuyDetailBean.getLeaderId() == null ? "系统用户" : "-");
            }
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x262 && resultCode == Activity.RESULT_OK) {
            PayeeMethodBean payeeMethodBean = (PayeeMethodBean) data.getSerializableExtra("PayeeMethodBean");
            setPayeeView(payeeMethodBean);
        }

        if (requestCode == 0x268 && resultCode == Activity.RESULT_OK) {
            ArrayList<ImageItem> imageList = data.getParcelableArrayListExtra("ImageList");
            if (imageList != null) {
                mImageList.clear();
                mImageList.addAll(imageList);
                mPayImageAdapter.notifyDataSetChanged();
            }

        }
    }

    private void initImageRv() {
        mPayImageAdapter = new CommonAdapter<ImageItem>(mContext, mImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = (ImageView) holder.getView(R.id.iv_item);


                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }

                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }

                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(mImageList.get(position).path) && TextUtils.isEmpty(mImageList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });

            }


        };


        mRvUserUpload.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvUserUpload.setAdapter(mPayImageAdapter);
        mRvUserUpload.setHasFixedSize(true);
        mRvUserUpload.setNestedScrollingEnabled(false);
    }

    private void setPayeeView(PayeeMethodBean payeeMethodBean) {
        if (payeeMethodBean == null) {
            return;
        }
        mPayeeId = payeeMethodBean.getId();
        mTvPayee.setText(payeeMethodBean.getBank());
        mTvName.setText(payeeMethodBean.getName());
        mTvAccount.setText(payeeMethodBean.getAccount());
    }

    @OnClick(R.id.ll_pay_type)
    void collectionWayClick() {
        if (mAskBuyDetailBean == null) {
            ToastUtil.showMessage(mContext, "网络错误，请稍后再试");
            return;
        }
        Intent intent = new Intent(mContext, CollectionWayActivity.class);
        if (mAskBuyDetailBean.getLeaderId() == null) {
            intent.putExtra("isCompany", true);
        } else {
            intent.putExtra("isCompany", false);
        }
        intent.putExtra("PayeeId", mPayeeId);
        startActivityForResult(intent, 0x262);
    }


    @OnClick(R.id.ll_pay_voucher)
    void payVoucherClick() {
        Intent intent = new Intent(mContext, PaymentVoucherActivity.class);
        intent.putExtra("ImageList", mImageList);
        startActivityForResult(intent, 0x268);
    }

    @OnClick(R.id.btn_submit)
    void submitClick() {
        if (TextUtils.isEmpty(mPayeeId)) {
            ToastUtil.showMessage(mContext, "请选择收款渠道");
            return;
        }

        if (mImageList.isEmpty()) {
            ToastUtil.showMessage(mContext, "请添加付款凭证");
            return;
        }

        httpCommitUploadFile(mImageList);
    }

    private void httpCommitUploadFile(ArrayList<ImageItem> customImageList) {
        final ArrayList<File> fileList = new ArrayList<>();


        for (ImageItem imageItem : customImageList) {
            if (!TextUtils.isEmpty(imageItem.path)) {
                fileList.add(new File(imageItem.path));
            }
        }
        try {
            FileBizFactory.createBiz().uploads(this, fileList, Url.FILE_TYPE_IMAGE, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    List<UploadFileBean> fileBeanList = (List<UploadFileBean>) data;
                    List<String> fileIds = new ArrayList<>();
                    for (UploadFileBean uploadFileBean : fileBeanList) {
                        fileIds.add(uploadFileBean.getId());
                    }

                    String ids = StringUtil.arrayList(fileIds);

                    httpCommit(ids);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            dismissLoadingDialog();
        }

    }


    private void httpCommit(String fid) {
        try {
            OrderBizFactory.createBiz().buyPay(this, mAskBuyDetailBean.getId(), mPayeeId, fid, mAskBuyDetailBean.getPointsInput(), new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ToastUtil.showMessage(mContext, "提交成功");
                    EventBus.getDefault().post(new EventMessage(EventTag.MY_STOCK_ORDER_LIST, mAskBuyDetailBean.getState()));
                    //                    httpGetDetail(mAskBuyBean.getId());
                    IntentUtil.goBackToActivity(OfflinePayActivity.this, MyStockActivity.class);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }
}
